import pyautogui
import pydirectinput
import time
import keyboard
import pygetwindow #兼容旧代码
import pygetwindow as gw
import ctypes
import win32gui
import win32con
import random
import sys
import io
import ctypes
import os
import fileinput
import subprocess
import progressbar
import threading
import datetime
from PIL import ImageGrab,Image
import utils

# 窗口位置，游戏启动后获取
x1 = 0
y1 = 0
game_title = '雷电模拟器'
file_path = r'D:\Software\leidian\LDPlayer9\dnplayer.exe'
def r():
    random_number = random.uniform(0.7, 0.9)
    time.sleep(random_number)
def rr():
    random_number = random.uniform(1.5, 2.0)
    time.sleep(random_number)
def rrr():
    time.sleep(15)
def sleep(t):
    time.sleep(t)
def click(x,y):
    pydirectinput.click(x+x1, y+y1)#点击
    rr()
def press(m):
    pydirectinput.press(m)#按键
    r()
def getpngfromShot2(png,_threshold=0.8,_show_print=True):
    small = Image.open(f"miyoushe/{png}.png")
    big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
    point = utils.getpngfromShot(small,big,_threshold=_threshold)
    if _show_print:
        print(png,point)
    return point
def make_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = win32gui.GetForegroundWindow()

        # 获取目标窗口
        windows = gw.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False
        
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is already the active window.")
            return True
        
        # 将窗口设置为活动窗口
        win32gui.ShowWindow(target_window, win32con.SW_RESTORE)  # 恢复窗口（如果它被最小化）
        win32gui.SetForegroundWindow(target_window)  # 设置为前景窗口
        
        print(f"Window '{window_title}' has been set as the active window.")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False
def is_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = ctypes.windll.user32.GetForegroundWindow()

        # 获取所有窗口
        windows = pygetwindow.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False

        # 获取目标窗口的句柄
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is the active window.")
            return True
        else:
            print(f"Window '{window_title}' is not the active window.")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False
def move_XY(window_title,new_x,new_y):
    try:
        # 获取窗口对象
        windows = pygetwindow.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return
        
        # 选择第一个匹配的窗口
        window = windows[0]
        hwnd = window._hWnd

        # 获取当前窗口的位置信息
        rect = window._rect
        current_width = rect.width
        current_height = rect.height

        # 使用 ctypes 调用 MoveWindow API 移动窗口
        ctypes.windll.user32.MoveWindow(hwnd, new_x, new_y, current_width, current_height, True)
        print(f"Window '{window_title}' moved to ({new_x}, {new_y}) while keeping its size.")
    except Exception as e:
        print(f"Error: {e}")
def getXY():
    #init
    global game_title
    
    while(True):
        make_window_active(game_title)
        sleep(0.5)
        if is_window_active(game_title):
            sleep(0.5)
            move_XY(game_title,0,0)
            break

    # 获取指定标题的程序窗口对象
    program_window = pygetwindow.getWindowsWithTitle(game_title)[0]
    # 获取窗口左上角的位置
    top_left_position = program_window.topleft
    print(top_left_position)
    global x1,y1,xing;
    x1 = top_left_position.x
    y1 = top_left_position.y
    xing = program_window
# 进度条
def getBar(_maxval):
    bar = progressbar.ProgressBar(maxval=_maxval, widgets=[
        progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
    ])
    bar.start()
    return bar

def launch_game():
    sleep(2)
    global file_path
    #C:\Program Files\Star Rail\Game\StarRail.exe
    game_name = os.path.basename(file_path)
    call = 'TASKLIST','/FI',f'imagename eq {game_name}'
    output = subprocess.check_output(call).decode('cp1252')
    if game_name in output:
        isLaunchGame = True
    else:
        isLaunchGame = False
    
    if not isLaunchGame:
        print("not running")
        try:
            # 调用subprocess模块来启动.exe文件
            # subprocess.Popen(file_path,creationflags=subprocess.CREATE_NEW_CONSOLE)
            game_process = subprocess.Popen(['start', '', file_path], shell=True)
            result = 1
        except FileNotFoundError as e:
            print("未能找到指定的.exe文件")
            result = 0
        except Exception as e:
            print("发生错误：", str(e))
            result = 0
            
        if(result == 0):
            print("脚本结束...")
            exit()
        else:
            print("等待模拟器启动...")
            bar=getBar(60)
            #启动程序到加载窗口出来
            for i in range(60):
                #print(str(i)+"-",end="")
                sleep(1) #等待游戏启动
                bar.update(i)
                if any(game_title in win.title for win in pygetwindow.getWindowsWithTitle(game_title)):
                    break
            bar.finish()
            #初始化位置，将程序放到左上角
            getXY()

            print("等待进入界面。。。")
            bar=getBar(60)
            for i in range(60):
                sleep(1) #等待游戏启动
                bar.update(i)
                loc = getpngfromShot2("米游社",_show_print=False)
                if loc!=0:
                    break;
            bar.finish()
            
            print("雷电模拟器 加载完毕。。。")
    else:
        print("running")
        getXY()

def close_game():
    sleep(2)
    file_name = os.path.basename(file_path)
    subprocess.run(["taskkill", "/F", "/IM", f"{file_name}"])

def open_miyoushe():
    sleep(2)  
    loc = getpngfromShot2("米游社")
    if loc!=0:
        click(loc[0],loc[1])
        sleep(10)
    getXY()
    loc = getpngfromShot2("青少年模式",_threshold=0.5)
    if loc!=0:
        click(loc[0]+20,loc[1]+20)
        sleep(1)
    loc = getpngfromShot2("下次再说")
    if loc!=0:
        click(loc[0]+20,loc[1]+20)
        sleep(1)
    
def sign_yuan():
    sleep(2)
    click(55,98) # 原神标签
    click(219,169) # 签到
    flag = 0
    bar = getBar(20)
    for i in range(20):
        sleep(1)
        bar.update(i)
        loc = getpngfromShot2("yuan_漏签",_threshold=0.8,_show_print=False)
        if loc!=0:
            print(loc[0],loc[1])
            sleep(2)
            flag += 1
            if flag > 2:break;
    if flag>0:
        if loc[1]<480:
            # screenshot = ImageGrab.grab()
            # color = screenshot.getpixel((x1, x1))
            # 202,536 131,599
            # 365,534 163
            # 528,533 163
            # 693,533 165
            # (233, 96, 68)#红点颜色
            red_x,red_y = 202,536
            signSucc = 0
            for i in range(8):
                if i==4: red_x,red_y = 202,746
                # color = screenshot.getpixel((red_x, red_y))
                # print(f"red_x,red_y={red_x},{red_y} color={color}")
                print(f"red_x,red_y={red_x},{red_y}")
                # if color==(233, 96, 68):
                #     click(red_x-70,red_y+60)
                #     sleep(1)
                #     break
                click(red_x-70,red_y+60)
                sleep(1)
                loc = getpngfromShot2("yuan_签到成功")
                if loc!=0:
                    print("原 签到成功。。。")
                    click(377,1189) # 关闭按钮
                    click(48,110) #返回
                    signSucc = 1
                    break
                red_x = red_x+(1*163)
            if signSucc==0:
                print("原 签到失败。。。返回")
                click(48,110) #返回

        else:
            print("yuan below")
            #TODO
        pass
    else:
        print("原，没找到漏签标签。。。返回")
        return        
def sign_zzz():
    sleep(2)
    click(148,94) #绝区零 标签
    click(89,170) #签到
    flag = 0
    bar = getBar(20)
    for i in range(20):
        sleep(1)
        bar.update(i)
        loc = getpngfromShot2("zzz_漏签",_threshold=0.8,_show_print=False)
        if loc!=0:
            print(loc[0],loc[1])
            sleep(2)
            flag += 1
            if flag > 2:break;
    if flag>0:
        if loc[1]<520:
            # screenshot = ImageGrab.grab()
            # color = screenshot.getpixel((x1, x1))
            # 196,709 196,919
            # 360,709 164
            # 522,709 162
            # 687,709 165
            # (255, 0, 0)#红点颜色
            red_x,red_y = 196,529
            signSucc = 0
            for i in range(8):
                if i==4: red_x,red_y = 196,741
                # color = screenshot.getpixel((red_x, red_y))
                # print(f"red_x,red_y={red_x},{red_y} color={color}")
                print(f"red_x,red_y={red_x},{red_y}")
                # if color==(255, 0, 0):
                #     click(red_x-70,red_y+60)
                #     sleep(1)
                #     break
                click(red_x-70,red_y+60)
                sleep(1)
                loc = getpngfromShot2("zzz_今日签到成功")
                if loc!=0:
                    print("z 签到成功。。。")
                    click(376,1185) # 关闭按钮
                    click(48,110) #返回
                    signSucc = 1
                    break;
                red_x = red_x+(1*163)
            if signSucc==0:
                print("z 签到失败。。。返回")
                click(48,110) #返回
        
        else:
            print("zzz below")
            #TODO
        pass
    else:
        print("z 没找到漏签标签。。。返回")
        return
def sign_xing():
    sleep(2)
    sleep(2)
    click(382,96) #星穹铁道 标签
    click(216,169) #签到
    flag = 0
    bar = getBar(20)
    for i in range(20):
        sleep(1)
        bar.update(i)
        loc = getpngfromShot2("xing_漏签",_threshold=0.8,_show_print=False)
        if loc!=0:
            print(loc[0],loc[1])
            sleep(2)
            flag += 1
            if flag > 2:break;
    if flag>0:
        if loc[1]<580:
            # screenshot = ImageGrab.grab()
            # color = screenshot.getpixel((x1, x1))
            # 193,816 192,1052
            # (255, 170, 42)#红点颜色
            red_x,red_y = 193,816
            signSucc = 0
            for i in range(8):
                if i==4: red_x,red_y = 192,1052
                # color = screenshot.getpixel((red_x, red_y))
                # print(f"red_x,red_y={red_x},{red_y} color={color}")
                print(f"red_x,red_y={red_x},{red_y} ")
                # if color==(255, 170, 42):
                #     click(red_x,red_y)
                #     sleep(1)
                #     break
                click(red_x,red_y)
                sleep(1)
                loc = getpngfromShot2("xing_今日签到成功")
                if loc!=0:
                    print("xing 签到成功。。。")
                    click(378,1155) # 关闭按钮
                    click(48,110) #返回
                    signSucc = 1
                    break
                red_x = red_x+(1*163)
            if signSucc ==0:
                print("xing 签到失败。。。返回")
                click(48,110) #返回
                return 

        else:
            print("xing below")
            #TODO
        pass
    else:
        print("xing 没找到漏签标签。。。返回")
        return
def sign_beng():
    sleep(2)
    sleep(2)
    sleep(2)
    click(250,99) #崩坏三 标签
    click(217,173) #签到
    flag = 0
    bar = getBar(20)
    for i in range(20):
        sleep(1)
        bar.update(i)
        loc = getpngfromShot2("beng_漏签",_threshold=0.8,_show_print=False)
        if loc!=0:
            print(loc[0],loc[1])
            sleep(2)
            flag += 1
            if flag > 2:break;
    if flag>0:
        if loc[1]<480:
            # screenshot = ImageGrab.grab()
            # color = screenshot.getpixel((x1, x1))
            # 200,533 200,745
            # 363,533 163
            # 527,533 164
            # 690,533 163
            # (254, 123, 122)#红点颜色
            red_x,red_y = 200,533
            signSucc = 0
            for j in range(8):
                if j==4: red_x,red_y = 200,745
                # color = screenshot.getpixel((red_x, red_y))
                # print(f"red_x,red_y={red_x},{red_y} color={color}")
                print(f"red_x,red_y={red_x},{red_y} ")
                # if color==(254, 123, 122):
                #     click(red_x,red_y)
                #     sleep(1)
                #     break
                click(red_x-70,red_y+60)
                sleep(1)
                loc = getpngfromShot2("beng_今日签到成功")
                if loc!=0:
                    print("beng 签到成功。。。")
                    click(379,1172) # 关闭按钮
                    click(48,110) #返回
                    signSucc = 1
                    break
                red_x = red_x+(1*163)
            if signSucc==0:
                print("beng 签到失败。。。返回")
                click(48,110) #返回

        else:
            print("beng below")
            #TODO
        pass
    else:
        print("beng 没找到漏签标签。。。返回")
        return
def daily():
    sleep(2)
    click(55,98) # 原神标签
    click(256,340) #酒馆
    click(700,509) #打卡
    click(118,342) #发现
    
    print("点赞。。。。。")
    for i in range(5):
        click(55,98) # 原神标签
        sleep(1)
        click(312,393) #第一条
        for j in range(10):
            sleep(1)
            loc = getpngfromShot2("yuan_点赞",_show_print=False)
            if loc!=0:
                click(loc[0]+10,loc[1]+10)
                sleep(1)
                break
        click(30,99) # 返回

    print("分享。。。。。")
    click(55,98) # 原神标签
    sleep(1)
    click(312,393) #第一条
    click(710,94) #右上角分享
    click(53,1182) #转发
    click(463,779) #确认转发
    sleep(3)
    loc = getpngfromShot2("yuan_拼图")
    if loc==0:
        print("没触发拼图。。。")
        click(30,99) # 返回
    else:
        print("触发拼图。。。")
        click(196,893) # 关闭拼图
        click(30,99) # 返回


def play():
    print("启动模拟器。。。")
    launch_game()

    print("打开米游社。。。")
    open_miyoushe()

    print("原神签到。。。")
    sign_yuan()

    print("绝区零签到。。。")
    sign_zzz()

    print("星穹铁道签到。。。")
    sign_xing()

    print("崩坏三签到。。。")
    sign_beng()

    print("每日签到点赞。。。")
    daily()


    print("关闭模拟器。。。")
    close_game()



if __name__ == "__main__":
    admin = ctypes.windll.shell32.IsUserAnAdmin()
    print("admin=="+str(admin))

    if admin:
        print("have admin")
        # 主程序写在这里
        try:
            play()
        except Exception as e:
            print(e)

        # input() # 防止退出
        exit(0)
    else:
        print("not admin")
        # 以管理员权限重新运行程序
        if len(sys.argv) > 1:
            ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__+" "+sys.argv[1], None, 3)
        else:
            ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__, None, 3)


